package com.springweb.unit5.config;

import java.io.IOException;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.core.io.FileSystemResource;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

import com.springweb.unit9.config.SecurityConfig;

@Configuration
// 启用SpringMVC
@EnableWebMvc
// 启用组件扫描
@ComponentScan(basePackages={"com.springweb.unit5", "com.springweb.unit7", "com.springweb.unit9"})
// 扫描Spring Security配置类
//@Import({SecurityConfig.class})
public class WebConfig extends WebMvcConfigurerAdapter {
	// 配置JSP试图解析器
	@Bean
	public ViewResolver viewResolver() {
		InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
		viewResolver.setPrefix("/");
		viewResolver.setSuffix(".jsp");
		viewResolver.setExposeContextBeansAsAttributes(true);
		viewResolver.setRedirectHttp10Compatible(false);
		// 设置jstl试图解析器
//		viewResolver.setViewClass(org.springframework.web.servlet.view.JstlView.class);
		return viewResolver;
	}
	
	// 配置multipart解析器
	// Spring内置了两个MultipartResolver的实现供我们选择:
	// 1.StandardServletMultipartResolver：依赖于Servlet 3.0对multipart请求的支持（始于Spring 3.1）。
//	@Bean
//	public MultipartResolver multipartResolver() throws IOException {
//		return new StandardServletMultipartResolver();
//	}
	// 2.CommonsMultipartResolver：使用Jakarta Commons FileUpload解析multipart请求
	@Bean
	public MultipartResolver multipartResolver() throws IOException {
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
		multipartResolver.setUploadTempDir(new FileSystemResource("/tmp/uploads"));
		// 最大的文件容量设置为2MB
		multipartResolver.setMaxUploadSize(2097152);
		// 最大的内存大小设置为0字节
		multipartResolver.setMaxInMemorySize(0);
		return multipartResolver;
	}
	// 设置静态资源处理
	@Override
	public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
		configurer.enable();
	}

}
